package com.xnew.filter;

import com.alibaba.fastjson.JSONObject;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.constant.Constant;
import com.xnew.utils.RedisUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//@Component
public class TokenFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}
	private boolean debug = true;
	@Override
	public void doFilter(ServletRequest request, ServletResponse red, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;

		HttpServletResponse response = (HttpServletResponse) red;
		response.setHeader("Access-Control-Allow-Origin",req.getHeader("Origin"));
		response.setHeader("Access-Control-Allow-Credentials","true");
		response.setHeader("Access-Control-Allow-Headers","authorization, content-type, token, times");
		response.setHeader("Access-Control-Allow-Methods","POST,GET");
		response.setHeader("Access-Control-Expose-Headers","X-forwared-port, X-forwarded-host");
		response.setHeader("Vary","Origin,Access-Control-Request-Method,Access-Control-Request-Headers");


		String requestURI = req.getRequestURI();
		if (requestURI.indexOf("/shiro-api/userLogin") != -1 || requestURI.indexOf("/shiro-api/login") != -1
				|| requestURI.indexOf("/shiro-api/login") != -1
				|| requestURI.indexOf("/process/") != -1 || requestURI.indexOf("/model/") != -1
				|| requestURI.indexOf("/task/") != -1 || requestURI.indexOf("/editor-app/") != -1
				|| requestURI.indexOf("/service/") != -1 || requestURI.indexOf("modeler.html") != -1 || requestURI.indexOf("initOrgAndUserResult") != -1
				|| requestURI.indexOf("/member-mediator/mediationApplicationController/addMedtBscInfoFromWeb") != -1
				|| requestURI.indexOf("/member-mediator/mediationApplicationController/selectMedtBscInfoByMedtNumber") != -1
				|| requestURI.indexOf("/member-manager/publicInfomation/") != -1
				|| requestURI.indexOf("/member-security/file/fileUploadCommon/fileUploadCommonForweb") != -1

				|| requestURI.indexOf("/member-manager/SsoApi/login") != -1 //单点登录接口
				|| requestURI.indexOf("/member-manager/SsoApi/SubSystemOrgReg") != -1 //门户机构注册接口
				|| requestURI.indexOf("/member-manager/SsoApi/logout") != -1 //退出接口
				|| requestURI.indexOf("/member-manager/SsoApi/updateToken") != -1 //刷新门户Token
		) {
			chain.doFilter(request, response);
			return;
		}

		String token = req.getHeader("token");
		if(requestURI.indexOf("/shiro-api/logout") != -1) {
			RedisUtil.del(token);
			returnNoLoginJson(request, response, "001", "退出成功");
		}

		// 判断是否有token，如果没有token，系统拒绝转发
		if (null != token && !"".equals(token)) {
			if(RedisUtil.exists("LOGIN_KICKET_OUT:"+token)) {
				RedisUtil.del("LOGIN_KICKET_OUT:"+token);
				returnNoLoginJson(request, response, "407", "登录用户被踢出，如非本人操作，请重新登录并修改密码");
				return;
			}
			String userStr = RedisUtil.get(token);
			if (null != userStr && !"".equals(userStr)) {
				SysUserInfo user = JSONObject.parseObject(userStr, SysUserInfo.class);
				req.getSession().setAttribute(Constant.LOGIN_USER, user);
//				RedisUtil.expire(token, 1800);
				RedisUtil.expire("AES_KEY:" + token, 1800);
				RedisUtil.expire("USER_ROLE:" + user.getUserInfoNo(), 1800);
				RedisUtil.expire("USER_ID:"+user.getUserInfoNo(), 1800);
				RedisUtil.expire("LOGIN_TYPE:"+token, 1800);
				chain.doFilter(request, response);
			} else {
				returnNoLoginJson(request, response, "404", "filter拦截用户未登录");
				return;
			}
		} else {
			returnNoLoginJson(request, response, "404", "filter拦截用户未登录");
			return;
		}
	}

	@Override
	public void destroy() {

	}

	/**
	 * 如果未登录，返回404信息
	 */
	private void returnNoLoginJson(ServletRequest request, ServletResponse response, String code, String message) {
		JSONObject json = new JSONObject();
		json.put("code", code);
		json.put("message", message);
		PrintWriter write = null;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/javascript;charset=utf-8");
		try {
			write = response.getWriter();
			write.print(json);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != write) {
				write.close();
			}
		}
	}

}
